package middle

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"synthesis-server/model"
	"time"
)

var jwtkey = []byte("sdu.edu.cn")
var str string
var TokenClaims Claims

type Claims struct {
	User model.User
	jwt.StandardClaims
}

func Setting(c *gin.Context, u *model.User) { //颁发token
	//println("正式进入了setting")
	expireTime := time.Now().Add(time.Hour * 12) //12个小时的有效期
	claims := &Claims{
		User: *u,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 60,
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(), //颁发时间
			Issuer:    "127.0.0.1",       //签名颁发者
			Subject:   "user token",      //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtkey) //形成加密串
	if err != nil {
		panic(err)
	}
	str = tokenString
	c.JSON(200, gin.H{
		"status": 1,
		"token":  tokenString,
		"type":   u.Type,
	})
}

//解析token
func Getting(c *gin.Context) {
	//println("进入解析token阶段")
	tokenString := c.GetHeader("sec-websocket-protocol")
	//println(tokenString)
	if tokenString == "" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": "verifyFailed",
		})
		c.Abort()
		return
	}
	TokenClaims = Claims{}
	token, err := jwt.ParseWithClaims(tokenString, &TokenClaims, func(token *jwt.Token) (interface{}, error) {
		return jwtkey, nil
	})
	if err != nil || !token.Valid { //出错或者token不对的情况
		panic(err)
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": "verifyFailed",
		})
		c.Abort()
		return
	}
	//fmt.Println("这是中间件解析token是否正确的部分：", TokenClaims.User)
}
